<template>
  <div class="app-container">

    <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery">
      <el-form-item slot="button">
        <el-button v-hasPermi="['miniProgram:renew:add']" type="success" @click="handleAdd">添加</el-button>
      </el-form-item>
      <template slot="selectRemote" slot-scope="{param}">
        <template v-if="param === 'admin_id_search'">
          <YxhySelectRemote
            :value.sync="queryParams.admin_id_search"
            :request-fn="queryUserAllList"
            :request-key="`name_search`"
            :response-id="`id`"
            :response-name="`chinese_name`"
            :placeholder="`请选择操作人`"
          />
        </template>
      </template>
    </YxhyTableQuery>

    <YxhyTableData :columns="columns" :data="tableList" :loading="loading">
      <!-- 插槽内容 -->
      <template #action>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <div class="table-action-panel">
              <el-button v-hasPermi="['miniProgram:renew:edit']" type="success" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <template v-if="scope.row.flag === 0">
                <el-button v-hasPermi="['miniProgram:renew:flag']" type="primary" size="mini" @click="handleSwitchFlag(scope.row)">启用</el-button>
              </template>
              <template v-else-if="scope.row.flag === 1">
                <el-button v-hasPermi="['miniProgram:renew:flag']" type="info" size="mini" @click="handleSwitchFlag(scope.row)">关闭</el-button>
              </template>
              <el-button v-hasPermi="['miniProgram:renew:edit']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="应用" prop="product_id">
          <YxhyTableDialogSelect
            ref="yxhyTableDialogSelectRefApp"
            :btn-text="`选择应用`"
            :table-key="`id`"
            :table-name="`product_name`"
            :detail-data="isEdit ? formDetail : null"
            :detail-id-key="`product_id`"
            :columns="columnsSelectApp"
            :query-params="queryParamsSelectApp"
            :query-columns="queryColumnsSelectApp"
            :request-fn="queryListApp"
            @selectResult="handleSelectResultApp"
          />
        </el-form-item>
        <el-form-item label="应用渠道ID" prop="channel">
          <YxhyTableDialogSelect
            ref="yxhyTableDialogSelectRefChannelApp"
            :btn-text="`选择APP渠道`"
            :table-key="`id`"
            :table-name="`name`"
            :detail-data="isEdit ? formDetail : null"
            :detail-id-key="`channel`"
            :columns="columnsSelectChannelApp"
            :query-params="queryParamsSelectChannelApp"
            :query-columns="queryColumnsSelectChannelApp"
            :request-fn="queryPageChannelAppList"
            @selectResult="handleSelectResultChannelApp"
          />
        </el-form-item>
        <el-form-item label="平台" prop="client">
          <el-radio-group v-model="form.client">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">安卓</el-radio>
            <el-radio :label="2">苹果</el-radio>
            <el-radio :label="3">小程序</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="更新类型" prop="update_force">
          <el-radio-group v-model="form.update_force">
            <el-radio :label="0">推荐更新</el-radio>
            <el-radio :label="1">强制更新</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="更新版本号" prop="new_version">
          <el-input v-model="form.new_version" placeholder="请输入更新版本号" />
        </el-form-item>
        <el-form-item label="APK更新链接" prop="update_link">
          <el-input v-model="form.update_link" placeholder="请输入APK更新链接" />
        </el-form-item>
        <el-form-item label="更新时间" prop="update_at">
          <el-date-picker
            v-model="form.update_at"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="更新说明" prop="desc">
          <el-input v-model="form.desc" type="textarea" placeholder="请输入更新说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { CLIENT, columnsSelectApp, columnsSelectChannelApp, columnsStatic, FLAG, UPDATE_FORCE } from './Ds.js'
import { queryUserAllList } from '@/api/system/account'
import { queryListApp } from '@/api/miniProgram/app'
import { addChannelApp, editChannelApp, queryPageChannelAppList, updateChannelSwitch } from '@/api/channel/channelApp'
import { addRenew, deleteRenew, editRenew, editRenewFlag, queryListRenew } from '@/api/miniProgram/renew'
import { updateChannelAdId } from '@/api/config/channelData'
export default {
  name: 'RenewList',
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      // 查询参数
      queryParams: {
      },
      // 查询表单
      queryColumns: [],
      loading: false,
      // 表格列
      columns: columnsStatic,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      form: {
        product_id: undefined,
        client: 1, // 0=未知 1=安卓 2=苹果 3=小程序
        update_force: 0, // 0-推荐更新 1-强制更新
        new_version: undefined,
        channel: undefined,
        update_link: undefined,
        desc: undefined, // 更新说明
        update_at: undefined, // 更新时间
        flag: 1 // 1-有效 0-失效
      },
      formDetail: null,
      // 表单校验
      rules: {
        product_id: [
          { required: true, message: '请选择应用', trigger: ['blur', 'change'] }
        ],
        new_version: [
          { required: true, message: '请输入更新版本号', trigger: ['blur', 'change'] }
        ],
        update_link: [
          { required: true, message: '请输入APK更新链接', trigger: ['blur', 'change'] }
        ],
        desc: [
          { required: true, message: '请输入更新说明', trigger: ['blur', 'change'] }
        ],
        update_at: [
          { required: true, message: '请选择更新时间', trigger: ['blur', 'change'] }
        ]
      },
      queryUserAllList,

      // 选择应用
      queryParamsSelectApp: {
        product_id_search: undefined,
        product_name_search: undefined
      },
      queryColumnsSelectApp: [
        {
          label: '',
          placeholder: '请输入应用ID',
          type: 'input',
          param: 'product_id_search'
        }, {
          label: '',
          placeholder: '请输入应用名称',
          type: 'input',
          param: 'product_name_search'
        }
      ],
      columnsSelectApp,
      queryListApp,

      // 选择APP渠道
      queryParamsSelectChannelApp: {
        channel_id_search: undefined,
        channel_name_search: undefined
      },
      queryColumnsSelectChannelApp: [
        {
          label: '',
          placeholder: '请输入渠道ID',
          type: 'input',
          param: 'channel_id_search'
        }, {
          label: '',
          placeholder: '请输入渠道名称',
          type: 'input',
          param: 'channel_name_search'
        }
      ],
      columnsSelectChannelApp,
      queryPageChannelAppList
    }
  },
  computed: {
    isEdit() {
      return ![undefined, ''].includes(this.form.id)
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      const res = await queryListRenew({
        ...this.queryPage,
        ...this.queryParams
      })
      res.data.forEach(e => {
        const { client, flag, update_force } = e
        e.update_force_text = UPDATE_FORCE[update_force]
        e.client_text = CLIENT[client]
        e.flag_text = FLAG[flag]
      })
      this.tableList = res.data
      this.total = res.total
      this.loading = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 清空搜索按钮操作 */
    handleClear() {
      this.init()
    },
    reset() {
      this.form = {
        product_id: undefined,
        client: 1, // 0=未知 1=安卓 2=苹果 3=小程序
        update_force: 0, // 0-推荐更新 1-强制更新
        new_version: undefined,
        channel: undefined,
        update_link: undefined,
        desc: undefined,
        update_at: undefined,
        flag: 1 // 1-有效 0-失效
      }
      this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs.yxhyTableDialogSelectRefApp.onReset()
        this.$refs.yxhyTableDialogSelectRefChannelApp.onReset()
      })
    },
    /** 接收应用选择 */
    handleSelectResultApp(rows) {
      const product_id_str = rows.map(item => item.id).toString()
      this.form.product_id = product_id_str
    },
    /** 接受APP渠道选择 */
    handleSelectResultChannelApp(rows) {
      const channel_id_str = rows.map(item => item.id).toString()
      this.form.channel = channel_id_str
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.title = '添加应用更新'
      this.reset()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true
      this.title = '修改应用更新'

      row.version_id = row.id
      this.form = JSON.parse(JSON.stringify(row))
      this.$nextTick(() => {
        this.formDetail = JSON.parse(JSON.stringify(row))
      })
    },
    /** 修改状态按钮操作 */
    handleSwitchFlag(row) {
      const { id, flag } = row
      const boolean_flag = flag === 1
      editRenewFlag({
        version_id: id,
        flag: boolean_flag ? 0 : 1
      }).then(() => {
        this.$modal.msgSuccess('操作成功')
        this.open = false
        this.init()
      })
    },
    /** 删除按钮 */
    handleDelete(row) {
      const { id } = row
      const _this = this
      this.$modal
        .confirm('确定要删除吗？')
        .then(function() {
          deleteRenew({
            version_id: id
          }).then(() => {
            _this.$modal.msgSuccess('删除成功')
            _this.init()
          })
        })
        .catch(() => {})
    },
    cancel() {
      this.open = false
    },
    submitForm() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.form.channel = this.form.channel || 0
          if (this.isEdit) {
            editRenew(this.form).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.init()
            })
          } else {
            addRenew(this.form).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.open = false
              this.init()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.link-panel .el-button + .el-button{
  margin-left: 0;
  margin-top: 10px;
}
.item-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 20px;
  .item-panel {
    width: 32%;
    background-color: #f8f8f8;
    padding: 10px;
    margin-bottom: 20px;
  }
}
.item-box:after {
  content: '';
  width: 30%;
}

.detail-hover {
  color: #409eff
}

.detail-hover:hover {
  cursor: pointer;
}

.detail-text {
  margin-left: 20px;
}
</style>
